package com.example.checkctf.View;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bjw.bean.ComBean;
import com.bjw.utils.FuncUtil;
import com.example.baselibrary.Base.BaseActivity;
import com.example.baselibrary.Bean.CheckResultBean;
import com.example.baselibrary.Bean.PickResultBean;
import com.example.baselibrary.Utils.Customer;
import com.example.baselibrary.Utils.FaceCj;
import com.example.baselibrary.Utils.FileUtils;
import com.example.baselibrary.Utils.HexToString;
import com.example.baselibrary.Utils.InstructUtils;
import com.example.baselibrary.Utils.LogUtil;
import com.example.baselibrary.Utils.MyBitmapUtils;
import com.example.baselibrary.Utils.StringSplitUtils;
import com.example.baselibrary.Utils.ThreadManager;
import com.example.baselibrary.Utils.TimeUtil;
import com.example.baselibrary.Utils.ToastUtil;
import com.example.checkctf.Interface.NetResult;
import com.example.checkctf.NetworkRequest.ResultManger;
import com.example.checkctf.ProcessorThink.FaceCheck;
import com.example.checkctf.ProcessorThink.QRcodeCheck;
import com.example.checkctf.R;
import com.example.checkctf.Utils.ChangeFaceResult;
import com.example.facechecklibrary.Interface.FaceAppear;
import com.example.facechecklibrary.View.FaceMask;
import com.example.facechecklibrary.constant.Global;
import com.example.idandiclibrary.IDandICHelp.IDAndICUtils.IDAndICHelper;
import com.example.idandiclibrary.IDandICHelp.Interface.IDAndICInterface;
import com.example.qrcodelibrary.QRCodeHelper.QRCodeHelper;
import com.example.qrcodelibrary.QRCodeInterface.QRGetMessageInterface;
import com.faceplusplus.api.FaceDetecter;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.List;

import static android.graphics.BitmapFactory.decodeByteArray;

//
public class MainActivity extends BaseActivity implements SurfaceHolder.Callback, Camera.PreviewCallback {

    //初始化 参数，以及 其他各项准备
    private static ImageView resultEmo;
    private static ImageView ivtest;
    private static TextView resultText;
    private static TextView tvPass;
    private static TextView messageTitle;
    private static TextView messageOne;
    private static LinearLayout llresult;
    private static LinearLayout llTwo;
    private static TextView messageTwoNumber;
    private static TextView messageTwoRoom;
    private static TextView messageTwoTicket;
    private SurfaceView svPreview;
    private FaceMask fmMask;
    private HandlerThread handleThread;
    private Handler detectHandler;
    private Camera mCamera;
    Activity activity;
    private int width = 640;
    private int height = 480;
    private FaceDetecter facedetecter;


    //验证逻辑声明参数
    private boolean isReadQRCode;   // 读取的是二维码
    private boolean isReadIDCode;   //读取的是身份证
    private boolean isReadICCode;   //读取的是IC卡

    //与 handler 配合  处理 验证信息
    private static final int PROCESSOR_QRCODE = 10;
    private static final int PROCESSOR_IDCODE = 20;
    private static final int PROCESSOR_ICCODE = 30;
    private static final int PROCESSOR_GATE = 40;
    private static final int PROCESSOR_FACE = 50;
    private static final int PICK_FACE = 60;
    private static final int CHECK_FACE = 70;
    private static final int INITIALIZATION_THREAD = 80;  //初始化线程，让线程开启然后去刷卡
    private static final int CONTINUE_BRUSH = 90;  //等线程初始化后 再去操作
    private MyHandler mMyHandler = new MyHandler(this);

    private static String basa64;
    //是否是在采集人脸，如果不采集人脸 那么久一直要进行人脸验证
    private static boolean PickFace;
    //当是在人脸录完检票 就停止 持续的人脸检票
    private static boolean FaceFirst;
    private static Runnable feceNeed;
    private int faceNumber;

    private static CheckResultBean checkResultBean = new CheckResultBean();
    private Bitmap bitmap;
    private Bitmap bitmap1;
    private Bitmap bitmap_collect;
    private static String qrCheck = "";
    private static long reqOne = 0;
    private static long reqTwo = 5000;
    private static long betweenTime = 3000;

    private static Runnable runnableID;
    private static Runnable runnableIC;
    private static Runnable runnableGate;

    //采集人脸成功后 的  对象，
    private static PickResultBean pickResultBean;

    private static String rowKey;
    private static Runnable iniThreadRunable;
    private Runnable gateRunable;
    private static String numberAll;

    public void clean(View view) {
        QRCodeHelper.sendGateMessage(Customer.CLEAR_A_TO_VOTE);
    }


    private static class MyHandler extends Handler {

        private WeakReference<MainActivity> activityWeakReference;

        public MyHandler(MainActivity activity) {
            activityWeakReference = new WeakReference<MainActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            final MainActivity activity = activityWeakReference.get();
            if (activity != null) {
                switch (msg.what) {
                    case PROCESSOR_QRCODE:
                        Date dateTwo = new Date();
                        reqTwo = dateTwo.getTime();
                        Bundle bundle = msg.getData();
                        String QRdate = bundle.getString("PROCESSOR_QRCODE_DATE");
                        numberAll = QRdate;
                        LogUtil.v("二维码返回" + QRdate);
                        sendRequset("1", QRdate, "");

                        break;
                    case PROCESSOR_IDCODE:

                        Date dateTwoID = new Date();
                        reqTwo = dateTwoID.getTime();
                        Bundle bundleID = msg.getData();
                        String IDdate = bundleID.getString("PROCESSOR_IDCODE");
                        LogUtil.v("身份证返回" + IDdate);
                        numberAll = IDdate;
                        sendRequset("2", IDdate, "");

                        break;
                    case PROCESSOR_ICCODE:
                        Date dateTwoIC = new Date();
                        reqTwo = dateTwoIC.getTime();
                        Bundle bundleIC = msg.getData();
                        String ICdate = bundleIC.getString("PROCESSOR_IDCODE");
                        LogUtil.v("IC卡返回" + ICdate);
                        numberAll = ICdate;
                        sendRequset("3", ICdate, "");

                        break;
                    case PROCESSOR_GATE:
                        Bundle bundleGate = msg.getData();
                        String GateDate = bundleGate.getString("PROCESSOR_GATE");
                        // 查询结果返回  这里去刷新界面  由于250ms 查询一次，所以这部只处理 查询结果，不处理 其他结果  2A1106000100000000002F
                        if (GateDate.length() == 22) {
                            tvPass.setText("剩余通行人数:" + InstructUtils.getInstance().showPersonNumber(GateDate) + " 人");
                        }
                        //根据返回的 是否可以通行人数的界面 进行界面切换   大于0 检票成功    等于0 请检票
                        if (PickFace) {
                            return;
                        }
                        if (InstructUtils.getInstance().showPersonNumber(GateDate) > 0) {
                            ChangeFaceResult.getInstance().changeFacePick(30, InstructUtils.getInstance().showPersonNumber(GateDate), activity, llresult, llTwo, resultEmo, tvPass, resultText, messageTitle, messageTwoNumber,
                                    messageTwoRoom, messageTwoTicket, messageOne);
                        } else {
                            CheckResultBean checkResultBean = new CheckResultBean();
                            ChangeFaceResult.getInstance().changeFace(1, checkResultBean, activity, llresult, llTwo, resultEmo, tvPass, resultText, messageTitle, messageTwoNumber,
                                    messageTwoRoom, messageTwoTicket, messageOne);
                        }

                        break;
                    case PROCESSOR_FACE:
                        //人脸采集完成后，就调用接口
                        if (rowKey != null) {
                            Date dateTwoFace = new Date();
                            reqTwo = dateTwoFace.getTime();
                            Bundle bundleFace = msg.getData();
                            sendRequset("4", rowKey, rowKey);
                            rowKey = null;
                            FaceFirst = false;
                        }
                        break;

                    case PICK_FACE:
                        if (null != basa64 && !basa64.equals("")) {
                            FaceCheck.getInstance().FacePick(checkResultBean, basa64);
                            //图片使用过后就清空，不然会一直循环
                            basa64 = "";
                            PickFace = false;
                            this.removeCallbacks(feceNeed);
                        }

                        break;

                    case CHECK_FACE:
                        //这里 要去 人脸  1   比 N
                        if (null != basa64 && !basa64.equals("")) {
                            FaceCheck.getInstance().OneFaceCheck(basa64);
//                            CheckResultBean.DataBean dataBean = new CheckResultBean.DataBean();
//                            dataBean.setBarcodeNo("A8ACF2DBAD03D0B86");
//                            checkResultBean.setData(dataBean);
//                            FaceCheck.getInstance().FacePick(checkResultBean, basa64);
                        }
                        break;

                    case INITIALIZATION_THREAD:
                        //初始化 二维码和三杆闸机
                        iniThreadRunable = new Runnable() {
                            @Override
                            public void run() {
                                QRCodeHelper.linkSerial(Customer.QRCODE_POINT, Customer.QRCODE_BOTE);
                                QRCodeHelper.linkSerialGate(Customer.GATE_POINT, Customer.GATE_BOTE);

                                // 初始化 身份证和IC卡
                                IDAndICHelper.OpenIDAndICard(activity);
                            }
                        };

                        ThreadManager.getThreadPool().execute(iniThreadRunable);

                        break;

                    case CONTINUE_BRUSH:
                        //处理 ID 和 IC 卡 一直查询的问题
                        GateQuery();
                        IDAndICFind();
                        break;
                    default:
                        throw new IllegalStateException("Unexpected value: " + msg.what);
                }

            }
        }
    }

    private static void sendRequset(String type, String qRdate, String rowKey) {
        if (qrCheck.equals(qRdate) && reqTwo - reqOne < betweenTime) {
            return;
        }
        if (null != qRdate) {
            qrCheck = qRdate;
            //首先 不为空， 第二，接口间隔为3秒，防止相同的卡重复检票
            QRcodeCheck.getInstance().checkTicketNeedFace(type, qRdate, rowKey);
            Date dateOne = new Date();
            reqOne = dateOne.getTime();
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        //处理 ID 和 IC 卡 一直查询的问题
//        IDAndICFind();
//        GateQuery();
        Message message = new Message();
        message.what = CONTINUE_BRUSH;
        mMyHandler.sendMessageDelayed(message, 1000);
    }

    private static void GateQuery() {

        runnableGate = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        QRCodeHelper.sendGateMessage(Customer.QUERY_NUMBER);
                        Thread.sleep(250);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }


            }
        };
        ThreadManager.getThreadPool().execute(runnableGate);

    }

    private static void IDAndICFind() {

        //身份证 和 Ic卡轮流 查询

        runnableID = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        IDAndICHelper.ReadIDCard();
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }

            }
        };
        ThreadManager.getThreadPool().execute(runnableID);

        runnableIC = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        IDAndICHelper.ReadICCard();
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        };
        ThreadManager.getThreadPool().execute(runnableIC);
    }

    @Override
    protected int getView() {
        return R.layout.activity_main;
    }

    @Override
    public void init() {
        //找控件
        resultEmo = (ImageView) findViewById(R.id.iv_result_emo);
        ivtest = (ImageView) findViewById(R.id.iv_test);
        resultText = (TextView) findViewById(R.id.tv_result);
        messageTitle = (TextView) findViewById(R.id.tv_message_title);
        messageOne = (TextView) findViewById(R.id.tv_message_one);
        llresult = (LinearLayout) findViewById(R.id.ll_result);
        llTwo = (LinearLayout) findViewById(R.id.ll_message_two);
        messageTwoNumber = (TextView) findViewById(R.id.tv_message_two_number);
        messageTwoRoom = (TextView) findViewById(R.id.tv_message_two_room);
        messageTwoTicket = (TextView) findViewById(R.id.tv_message_two_ticket);
        svPreview = (SurfaceView) findViewById(R.id.sv_preview_track);
        fmMask = (FaceMask) findViewById(R.id.fm_mask_track);
        tvPass = (TextView) findViewById(R.id.tv_pass);

        //初始化人脸资源
        facedetecter = new FaceDetecter();
        facedetecter.init(this, Global.FACEPP_KEY);
        facedetecter.setTrackingMode(true);

        activity = this;
        handleThread = new HandlerThread("dt");
        handleThread.start();
        detectHandler = new Handler(handleThread.getLooper());
        svPreview.getHolder().addCallback(this);
        svPreview.setKeepScreenOn(true);
//        Message message = new Message();
//        message.what = INITIALIZATION_THREAD;
//        mMyHandler.sendMessageDelayed(message, 3000);
        mMyHandler.sendEmptyMessage(INITIALIZATION_THREAD);

        // 绘制人脸框 是否出现人脸回调
        FaceMask.setFaceAPPearListener(new FaceAppear() {
            @Override
            public void faceAppear(boolean s) {
                if (s) {
                    ToastUtil.showToast("人脸出现了");
                } else {

                }
            }
        });

        //获取工控机所有串口
        if (QRCodeHelper.preperQRFinder()) {
            List<String> qrList = QRCodeHelper.getDevicePorts();
            StringBuffer stringBuffer = new StringBuffer();

            for (int i = 0; i < qrList.size(); i++) {
                stringBuffer.append("串口+" + i + "+： " + qrList.get(i) + "\n");
            }
            LogUtil.v(stringBuffer + "");
        } else {
            LogUtil.v("获取串口编号失败");
        }


//
        //二维码和三杆闸机接口返回
        QRCodeHelper.setQRGetMessageListener(new QRGetMessageInterface() {
            @Override
            public void getQRMessage(final ComBean comBean) {

                Message message = Message.obtain();
                message.what = PROCESSOR_QRCODE;
                Bundle bundle = new Bundle();
                String decode = HexToString.decode(FuncUtil.ByteArrToHex(comBean.bRec));
                bundle.putString("PROCESSOR_QRCODE_DATE", decode.trim());
                message.setData(bundle);
                mMyHandler.sendMessage(message);
            }

            @Override
            public void getGateMessage(final ComBean comBean) {
                Message message = Message.obtain();
                message.what = PROCESSOR_GATE;
                Bundle bundle = new Bundle();
                String decode = FuncUtil.ByteArrToHex(comBean.bRec);
                bundle.putString("PROCESSOR_GATE", decode.trim());
                message.setData(bundle);
                mMyHandler.sendMessage(message);

            }
        });

        //身份证和IC卡返回的信息
        IDAndICHelper.setIDAndICListener(new IDAndICInterface() {
            @Override
            public void showIDMessage(final String s) {
                // 获取到身份证信息，该咋办
                Message message = Message.obtain();
                message.what = PROCESSOR_IDCODE;
                Bundle bundle = new Bundle();
                bundle.putString("PROCESSOR_IDCODE", s.trim());
                message.setData(bundle);
                mMyHandler.sendMessage(message);
            }

            @Override
            public void showICMessage(final String s) {

                // 获取到IC卡信息，该咋办
                Message message = Message.obtain();
                message.what = PROCESSOR_ICCODE;
                Bundle bundle = new Bundle();
                bundle.putString("PROCESSOR_ICCODE", s.trim());
                message.setData(bundle);
                mMyHandler.sendMessage(message);
            }
        });

        ResultManger.setNetResultListener(new NetResult() {
            @Override
            public void netResult(final int type, final CheckResultBean s) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ChangeFaceResult.getInstance().changeFace(type, s, MainActivity.this, llresult, llTwo, resultEmo, tvPass, resultText, messageTitle, messageTwoNumber,
                                messageTwoRoom, messageTwoTicket, messageOne);
                        //type 是3 的时候，是检票成功 查看可通行人数，然后发送相关人数让人通行
                        if (type == 3) {
                            passPersonSet(s);
                        }

                    }
                });
            }

            @Override
            public void faceAcceptResult(CheckResultBean s) {
                //需要录入 人脸信息，通过 现在去获取人脸信息，然后去网络请求
                PickFace = true;
                FaceFirst = true;
                basa64 = null;
                final Message message = new Message();
                message.what = PICK_FACE;
                checkResultBean = s;
                feceNeed = new Runnable() {
                    @Override
                    public void run() {
                        if (PickFace) {
                            if (null != basa64 && !basa64.equals("")) {
                                PickFace = false;
                                mMyHandler.sendMessage(message);

                            } else {
                                LogUtil.v("需要录入人脸，但是没有找到人脸，所以我就要一直找");
                                mMyHandler.postDelayed(this, 2000);
                            }
                        }
                    }
                };
                mMyHandler.post(feceNeed);


            }

            @Override
            public void faceSuccess(int type, String s) {
                //人脸添加成功，继续去检票  只要有 rowkey 那么就可以成功的进行人脸识别   type 4     还要去切换界面
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ChangeFaceResult.getInstance().changeFacePick(10, 0, MainActivity.this, llresult, llTwo, resultEmo, tvPass, resultText, messageTitle, messageTwoNumber,
                                messageTwoRoom, messageTwoTicket, messageOne);
                    }
                });
//                Message message = new Message();
//                message.what = PROCESSOR_FACE;
                if (rowKey != null) {
                    rowKey = null;
                }
                rowKey = s;
                mMyHandler.sendEmptyMessage(PROCESSOR_FACE);

            }

            @Override
            public void faceDefut() {
                // 添加人脸失败，重新检票  只是切换界面
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ChangeFaceResult.getInstance().changeFacePick(20, 0, MainActivity.this, llresult, llTwo, resultEmo, tvPass, resultText, messageTitle, messageTwoNumber,
                                messageTwoRoom, messageTwoTicket, messageOne);
                    }
                });

            }

            @Override
            public void oneFaceCheck(int type, String s) {
                //人脸对比成功，那么就去人脸闸机验证
                rowKey = s;
                mMyHandler.sendEmptyMessage(PROCESSOR_FACE);
            }
        });
        //测试 测试
//        StringSplitUtils.getInstance().StingQuerSpl("2A1106000400000000002F");
    }

    //可通行人数检测 然后指定人数
    private void passPersonSet(CheckResultBean s) {
        int passPerson = s.getData().getPassPersonSum();
        String pernumbre = InstructUtils.getInstance().personNumber(passPerson);
        QRCodeHelper.sendGateMessage(pernumbre);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

        try {
            mCamera = Camera.open(0);
            mCamera.setDisplayOrientation(90);
            Camera.Parameters para = mCamera.getParameters();


            Point showingArea = new Point();
            WindowManager wm = (WindowManager) getSystemService(
                    Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            int screenWidth = display.getWidth();
            int screenHeight = display.getHeight();

            int topHeight = dip2px(activity, 25 + 44);//状态栏+titlebar
            showingArea.set(screenWidth, screenHeight - topHeight);

            width = 640;
            height = 480;
            // 预览变形的问题
            Log.e("size", "size w:" + width + "--h:" + height);
        /*:1920--h:1080
09-19 15:30:11.068 19768-19768/com.hss01248.facedemo E/size: size w:1440--h:1080
09-19 15:30:11.068 19768-19768/com.hss01248.facedemo E/size: size w:1280--h:720
09-19 15:30:11.068 19768-19768/com.hss01248.facedemo E/size: size w:1056--h:864
09-19 15:30:11.068 19768-19768/com.hss01248.facedemo E/size: size w:960--h:720
09-19 15:30:11.068 19768-19768/com.hss01248.facedemo E/size: size w:720--h:480
09-19 15:30:11.068 19768-19768/com.hss01248.facedemo E/size: size w:640--h:480
09-19 15:30:11.068 19768-19768/com.hss01248.facedemo E/size: size w:352--h:288
09-19 15:30:11.068 19768-19768/com.hss01248.facedemo E/size: size w:320--h:240*/

            para.setPreviewSize(width, height);
            mCamera.setParameters(para);
        } catch (Exception e) {
            ToastUtil.showToast("无法找到摄像头，请确定摄像头已连接");
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        if (mCamera == null) {
            return;
        }
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.setDisplayOrientation(90);
            mCamera.startPreview();
            mCamera.setPreviewCallback(this);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mCamera == null) {
            return;
        }
        mCamera.setPreviewCallback(null);
        mCamera.stopPreview();
        mCamera.release();
        mCamera = null;

    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    private Point getBestCameraResolution(Camera.Parameters parameters, Point screenResolution) {
        float tmp = 0f;
        float mindiff = 100f;
        float x_d_y = (float) screenResolution.x / (float) screenResolution.y;
        Camera.Size best = null;
        List<Camera.Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();
        for (Camera.Size s : supportedPreviewSizes) {
            tmp = Math.abs(((float) s.height / (float) s.width) - x_d_y);
            if (tmp < mindiff) {
                mindiff = tmp;
                best = s;
            }
        }
        return new Point(best.width, best.height);
    }

    @Override
    public void onPreviewFrame(final byte[] data, final Camera camera) {
        camera.setPreviewCallback(null);
        if (mCamera == null) return;
        detectHandler.post(new Runnable() {
            @Override
            public void run() {
                int is = 0;
                final byte[] ori = new byte[width * height];
                for (int x = width - 1; x >= 0; x--) {
                    for (int y = height - 1; y >= 0; y--) {
                        ori[is++] = data[y * width + x];
                    }
                }
                final FaceDetecter.Face[] faceinfo = facedetecter.findFaces(ori, height, width);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //这里是去画框 给人脸
                        fmMask.setFaceInfo(faceinfo);
                    }
                });

                if (null != faceinfo) {
                    //  如果有人脸出现， 那么久保存下来
                    faceNumber++;
                    if (faceNumber > 5) {
                        faceNumber = 0;
                        coseToBase64(data, camera);
                    }
                }
                try {
                    camera.setPreviewCallback(MainActivity.this);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        });
    }

    //这个方法处理图片 后期需要放在 子线程里面
    private void coseToBase64(byte[] data, Camera camera) {

        try {
            Camera.Size previewSize = camera.getParameters().getPreviewSize();//获取尺寸,格式转换的时候要用到
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            newOpts.inJustDecodeBounds = true;
            YuvImage yuvimage = new YuvImage(
                    data,
                    ImageFormat.NV21,
                    previewSize.width,
                    previewSize.height,
                    null);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            yuvimage.compressToJpeg(new Rect(0, 0, previewSize.width, previewSize.height), 100, baos);// 80--JPG图片的质量[0-100],100最高
            final byte[] rawImage = baos.toByteArray();
//        将rawImage转换成bitmap
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.ARGB_4444;

            bitmap = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length, options);

            if (bitmap != null) {
                bitmap1 = MyBitmapUtils.rotateBitmap(bitmap, 270, true);
            }

            FaceCj.getPrintSize(FaceCj.getBitmapSize(bitmap));

            //经过测试  bitmap1，不为空的情况下，bitmap_collect为空，是剪裁里面 检查不到人脸，返回为空
            if (bitmap1 != null) {
                bitmap_collect = FaceCj.cutFace(bitmap1, MainActivity.this);

            }


            if (bitmap_collect != null) {
                basa64 = MyBitmapUtils.bitmapToBase64(bitmap_collect);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ivtest.setImageBitmap(bitmap_collect);
                    }
                });

                //FaceFirst 为  false ，那么检测到人脸 就需要去进行 人脸 1：N 对比  然后验证
                if (!FaceFirst) {
                    mMyHandler.sendEmptyMessage(CHECK_FACE);
                }

                //  Environment.getExternalStorageDirectory().toString() + File.separator + Customer.FOLDER_NAME,
                MyBitmapUtils.saveBitmap(bitmap_collect, new File(Environment.getExternalStorageDirectory().toString() + File.separator + Customer.FOLDER_NAME + File.separator + "zyf.png"));

            }

        } catch (Exception e) {
            LogUtil.v("图片回收异常");
        }

    }
//        bitmap.recycle();
//        bitmap1.recycle();
//        bitmap_collect.recycle();


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
